﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;
using System.Net;
using System.Security;
using System.Xml;
using System.IO;
namespace CardID
{
    
    [AttributeUsage(AttributeTargets.Method)]
    public class soapExtsAttribute :
                                    SoapExtensionAttribute
    {
        private int m_Priority = 0;

        public override Type ExtensionType
        {
            get { return typeof(soapExts); }
        }

        public override int Priority
        {
            get { return m_Priority; }
            set { m_Priority = value; }
        }
    }
     
    class soapExts:SoapExtension
    {
        public Stream oldStream;
        public Stream newStream;
        public Stream outputStream;
        public XmlDocument xmldoc;
        public override object GetInitializer(
                                  Type serviceType)
        {
            return null;
        }
        public override object GetInitializer(
                          LogicalMethodInfo methodInfo,
                          SoapExtensionAttribute attribute)
        {
            return null;
        }
        public override void Initialize(object initializer)
        {
            return;
        }
       
        public override Stream ChainStream(Stream stream)
        {
           //this.outputStream = stream;
            oldStream = stream;
            newStream = new MemoryStream();
            return newStream;
        }
        private String ExtractFromStream(Stream target)
        {
            if (target != null)
                return (new StreamReader(target)).ReadToEnd();
            return "";
        }
        public string getXMLFromCache()
        {
            newStream.Position = 0; // start at the beginning!
            string strSOAPresponse = ExtractFromStream(newStream);
            return strSOAPresponse;
        }
        // Access data and edit soap
        public override void ProcessMessage(SoapMessage message)
        {
            xmldoc = new XmlDocument();
            switch (message.Stage)
            {
                case SoapMessageStage.BeforeDeserialize:
                    logMessageDeserialize(message); break;
                case SoapMessageStage.AfterSerialize:
                    logMessageSerialize(message); break;

                case SoapMessageStage.AfterDeserialize:
                    //logMessageDeserialize(message);break;
                case SoapMessageStage.BeforeSerialize:
                    //logMessageSerialize(message);break;
                default:
                    break;
            }
        }
        public void logMessageSerialize(SoapMessage message)

        {
            //Copy(newStream, oldStream);
           
            StreamReader reader = new StreamReader(newStream);
            StreamWriter writer = new StreamWriter(oldStream);

            string soap = getXMLFromCache();
            writer.WriteLine(soap);
            writer.Flush();

            //xml.LoadXml(soap);
           // WriteOutput(soap);
        }
        public void logMessageDeserialize(SoapMessage message)
        {
            //StreamReader reader = new StreamReader(oldStream);
            //StreamWriter writer = new StreamWriter(newStream);

           // string soap = reader.ReadToEnd();
           // xmldoc.LoadXml(soap);
            //xmldoc.GetElementsByTagName("paymentInfo").Item(0).InnerXml = "Payment success";
           // soap = xmldoc.InnerXml;
           // soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?><SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://bkpay.local/transaction/server/api\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><SOAP-ENV:Body><ns1:makePaymentResponse><return xsi:type=\"ns1:MakePaymentResponse\"><tokenID xsi:type=\"xsd:string\">177258d6e1a4aae7721a284e330cd230</tokenID><actionType xsi:type=\"xsd:string\">CREATED</actionType><timestamp xsi:type=\"xsd:int\">1325476389</timestamp><ack xsi:type=\"xsd:boolean\">true</ack><paymentInfo xsi:type=\"xsd:string\">Payment success</paymentInfo></return></ns1:makePaymentResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
           
           // writer.WriteLine(soap);
            //writer.Flush();
            Copy(oldStream, newStream);

            string soap = getXMLFromCache();

            //System.Runtime.Remoting.Messaging.CallContext.SetData(
                              //"SOAPResponse", a);
            
            WriteOutput(soap);
            newStream.Position = 0;
        }
        public void WriteOutput(string message)
        {
            FileStream fs = new FileStream("C:\\log.xml", FileMode.Append,
                             FileAccess.Write);

            StreamWriter w = new StreamWriter(fs);
            //w.WriteLine("-----Response at " + DateTime.Now.ToString());
            w.WriteLine(message);
            w.Flush();
            w.Close();

        }
        private void Copy(Stream from, Stream to)
        {
            TextReader reader = new StreamReader(from);
            TextWriter writer = new StreamWriter(to);
            writer.WriteLine(reader.ReadToEnd());
            writer.Flush();
        }
        public void Test(string xml) {
        using (XmlReader xr = XmlReader.Create(
                new StringReader(xml))) {
            try {
                while (xr.Read()) { }
                Console.WriteLine("Pass");
            } catch (Exception ex) {
                Console.WriteLine("Fail: " + ex.Message);
            }
        }
       }
    }
}
